package com.george.auth.handler;

import com.alibaba.fastjson.JSON;
import com.george.auth.service.TokenServiceImpl;
import com.george.auth.vo.LoginUserVO;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @title: LogoutSuccessHandlerImpl.java
 * @description: 登录退出处理类
 * @author: George
 * @date: 2023/6/13 16:34
 */
@Configuration
@AllArgsConstructor
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    private final TokenServiceImpl tokenService;

    /**
     * 退出处理
     * 前面配置了外部访问路径：/login/logout
     *
     * @param request
     * @param response
     * @param authentication
     * @author :George
     * @date : 2021/10/13 19:51
     * @return: void
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        LoginUserVO loginUser = tokenService.getLoginUser(request);
        if (loginUser != null) {
            // 删除用户token缓存记录
            tokenService.delLoginUser(loginUser.getToken());
        }
        Map<Object, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("msg", "退出成功");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(JSON.toJSONString(map));
    }
}

